package com.haiertvbic.tvwa;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.haiertvbic.tvwa.model.LocalCodeBean;
import com.haiertvbic.tvwa.model.ProgramBean;
import com.haiertvbic.tvwa.model.SingleHandler;
import com.haiertvbic.tvwa.network.EPGWeb;
import com.haiertvbic.tvwa.protocol.CAEProtocol;
import com.haiertvbic.tvwa.util.AppManager;
import com.haiertvbic.tvwa.util.IsExit;
import com.haiertvbic.tvwa.util.LocateToast;
import com.haiertvbic.tvwa.util.ProduceThread;
import com.haiertvbic.tvwa.util.SLog;
import com.haiertvbic.tvwa.util.SetActivityView;
import com.haiertvbic.tvwa.util.SwitchChannel;

public class ProChannelActivity extends Activity {

	private static final String TAG = null;
	protected static final int GET_PROSTATION_FAIL = 03;
	protected static final int GET_PROSTATION_SUC = 04;
	private static final int GET_LOCAL_CODE_FAIL = 05;
	public static TextView showTime_3;
	public SingleHandler sHandler;
	private int pro_id;
	private View view;
	private TextView cha_name;
	private TextView pro_name;
	private TextView start_time;
	private ListView pro_cha_list;
	private ProgressBar bar_on_cha;
	private ArrayList<String[]> result_list;
	private ArrayList<ProgramBean> pro_cha_list1;
	private String chaName;
	private int chaId;
	private int[] cha_id;
	private boolean isHide;
	private int currentCha = -200;
	private int switchCha = -200;
	private Handler handler;
	private boolean canSwitch;

	/**
	 * 
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.program_channel);
		view = SetActivityView.setActivityView(getWindow(), getWindowManager());
		AppManager.activityList.add(this);

		Intent intent = getIntent();
		pro_id = intent.getIntExtra("PRO_ID", -1);
		String s = intent.getStringExtra("PRO_NAME");
		s = s.replaceAll("[0-9]", "");
		chaName = s;
		SLog.v("fav", "获取的PROID----》" + pro_id + "---------------PRO_NAME"
				+ chaName);
		initView();
		
		getResultPre();
		sHandler = SingleHandler.returnHandler();
		sHandler.setTextView(showTime_3);
		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				switch (msg.what) {

				case GET_PROSTATION_FAIL:
					// 获取频道数据失败，消失加载数据进度条
					// progressDialog.dismiss();
					bar_on_cha.setVisibility(View.GONE);
					LocateToast.locateToast(ProChannelActivity.this, 200,
							"获取节目信息失败，请返回重试");
					break;
				case GET_PROSTATION_SUC:
					// 获取数据成功，适配显示数据，消失加载数据的进度条
					bar_on_cha.setVisibility(View.GONE);
					pro_cha_list.setAdapter(new ProChaAdapter());
					canSwitch = true;
					break;
				case GET_LOCAL_CODE_FAIL:
					// 获取地域码失败
					LocateToast.locateToast(ProChannelActivity.this, 200,
							"获取地域码失败，请返回重试");
					break;
				case 0:
					LocateToast.locateToast(ProChannelActivity.this, 200,
							"读取换台信息失败");
					break;

				case 4004500:
					LocateToast.locateToast(ProChannelActivity.this, 200,
							"换台成功 ");
					currentCha = switchCha;
					try {
						Thread.sleep(4000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					break;

				case 4004501:
					LocateToast.locateToast(ProChannelActivity.this, 200,
							"此频道不存在");
					break;

				case 4004502:
					LocateToast.locateToast(ProChannelActivity.this, 200,
							"请插入或重新插拔CRB");
					break;

				case 4004503:
					LocateToast.locateToast(ProChannelActivity.this, 200,
							"您未设置 CRB");
					break;

				case -2002:
					LocateToast.locateToast(ProChannelActivity.this, 200,
							"连接断开");
					break;

				default:
					break;
				}
			}

		};
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		isHide = true;

	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		if (isHide) {
			// FavoriteChannelActivity.fView.setVisibility(View.INVISIBLE);
			ChannelProActivity.view.setVisibility(View.INVISIBLE);
		}
	}

	/**
	 * 初始化界面控件
	 */
	private void initView() {
		showTime_3 = (TextView) findViewById(R.id.show_time_3);
		cha_name = (TextView) findViewById(R.id.cha_name);
		pro_name = (TextView) findViewById(R.id.pro_name);
		start_time = (TextView) findViewById(R.id.start_time);
		pro_cha_list = (ListView) findViewById(R.id.pro_cha_list);
		bar_on_cha = (ProgressBar) findViewById(R.id.bar_on_cha);
		pro_name.setText(chaName);
		pro_cha_list.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				// Toast.makeText(ProChannelActivity.this, ""+arg2,
				// 1000).show();
				chaId = cha_id[arg2];
				if (canSwitch && currentCha != chaId) {
					SwitchChannel.switchChannel(ProChannelActivity.this, chaId,
							handler);
					switchCha = chaId;
				}

				ProduceThread.seconds = 60;
			}

		});
		pro_cha_list.setOnItemSelectedListener(new OnItemSelectedListener() {

			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				ProduceThread.seconds = 60;

			}

			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub

			}

		});
	}

	/**
	 * 按下按键时的反应
	 */
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		ProduceThread.seconds = 60;
		if (keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
			sHandler.setTextView(ChannelProActivity.showTime_2);
			finish();
		} else if (keyCode == KeyEvent.KEYCODE_BACK) {
			ProduceThread.canRun = false;
			ProduceThread.exit = false;
			IsExit.isExit(this);
		}
		return super.onKeyDown(keyCode, event);
	}

	/**
	 * 
	 * @author lb
	 * 
	 */
	// private class ProChaAsyncTask extends AsyncTask<Integer, Void, List> {
	//
	// @Override
	// protected List doInBackground(Integer... params) {
	// return getResultPre();
	// }
	//
	// @Override
	// protected void onPostExecute(List result) {
	// super.onPostExecute(result);
	// if (result == null) {
	// SLog.v("lfav", "结果为null");
	// LocateToast.locateToast(ProChannelActivity.this, 200,
	// "获取节目情况失败，请退出重试");
	// return;
	// }
	// pro_cha_list.setAdapter(new ProChaAdapter());
	// bar_on_cha.setVisibility(View.GONE);
	// canSwitch = true;
	// }

	/**
	 * 填充的adapter，节目在其他频道播放的情况
	 * 
	 * @author sun
	 */
	public class ProChaAdapter extends BaseAdapter {

		public int getCount() {
			// TODO Auto-generated method stub
			return pro_cha_list1.size();
		}

		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			if (convertView == null)
				convertView = LayoutInflater.from(ProChannelActivity.this)
						.inflate(R.layout.pro_cha_list_item, null);
			TextView chaName = (TextView) convertView
					.findViewById(R.id.cha_name);
			TextView proName = (TextView) convertView
					.findViewById(R.id.pro_name);
			TextView staTime = (TextView) convertView
					.findViewById(R.id.start_time);
			chaName.setText(result_list.get(0)[position]);
			proName.setText(result_list.get(1)[position]);
			staTime.setText(result_list.get(2)[position]);

			return convertView;
		}
	}

	// }

	/**
	 * 得倒节目在其他台播放的数据
	 */
	public void getResultPre() {
		new Thread() {
			public void run() {
				bar_on_cha.setVisibility(View.VISIBLE);
				LocalCodeBean loc_cod_bean = CAEProtocol.getLocalCode();
				if (loc_cod_bean == null) {
					// Looper.prepare();
					// LocateToast.locateToast(ProChannelActivity.this, 200,
					// "获取地域码失败，请返回重试");
					// Looper.loop();
					// Looper.myLooper().quit();
					handler.sendEmptyMessage(GET_LOCAL_CODE_FAIL);
					// return null;
				}

				if (loc_cod_bean.getReturn_code() == 4006301) {
					// Looper.prepare();
					// LocateToast.locateToast(ProChannelActivity.this, 200,
					// "获取地域码失败，请返回重试");
					// Looper.loop();
					// Looper.myLooper().quit();
					handler.sendEmptyMessage(GET_LOCAL_CODE_FAIL);
				} else {
					try {
						pro_cha_list1 = EPGWeb.getSituation(
								ProChannelActivity.this, pro_id,
								loc_cod_bean.getCity() + "");
					} catch (Exception e) {
						// TODO Auto-generated catch block
						if (pro_cha_list1 == null) {
							// Looper.prepare();
							// LocateToast.locateToast(ProChannelActivity.this,
							// 200, "获取节目信息失败，请返回重试");
							// Looper.loop();
							// Looper.myLooper().quit();
							handler.sendEmptyMessage(GET_PROSTATION_FAIL);
							// return null;
						}
					}
					if (pro_cha_list1 != null) {
						String[] cha_names = new String[pro_cha_list1.size()];
						String[] pro_names = new String[pro_cha_list1.size()];
						String[] sta_times = new String[pro_cha_list1.size()];
						cha_id = new int[pro_cha_list1.size()];
						for (int i = 0; i < pro_cha_list1.size(); i++) {
							ProgramBean proBean = pro_cha_list1.get(i);
							cha_names[i] = proBean.getCname();
							pro_names[i] = proBean.getPn();
							cha_id[i] = proBean.getCid();
							String s = proBean.getPstime() + "c";
							s = s.replace(":00c", "");
							sta_times[i] = s;
						}
						result_list = new ArrayList<String[]>();
						result_list.add(cha_names);
						result_list.add(pro_names);
						result_list.add(sta_times);
						handler.sendEmptyMessage(GET_PROSTATION_SUC);
						// return result_list;
					} else {
						handler.sendEmptyMessage(GET_PROSTATION_FAIL);
					}
				}
			};
		}.start();

	}
}
